package com.dcits.loadtest.common.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xuwangcheng
 * @version 1.0.0
 * @description
 * @date 2019/9/17 21:14
 */
public class LoadTestUtil {
    /**
     * 当前可用
     */
    private static final List<Integer> availablePool = new ArrayList<>();

    private static final Object lock = new Object();

    static {
        availablePool.add(0);
        availablePool.add(1);
        availablePool.add(2);
        availablePool.add(3);
        availablePool.add(4);
        availablePool.add(5);
        availablePool.add(6);
        availablePool.add(7);
        availablePool.add(8);
        availablePool.add(9);
    }

    public static Integer getLock () {
        synchronized(lock) {
            //可用客户端不足
            if (availablePool.size() < 1) {
                //等待释放
                while (availablePool.size() < 1) {
                    try {
                        lock.wait(800);
                    } catch (InterruptedException e) {

                    }
                }
            }
            Integer i = availablePool.get(0);
            availablePool.remove(i);
            return i;
        }
    }

    public static void putLock (Integer i) {
        synchronized (lock) {
            if (i != null && availablePool.size() < 10) {
                availablePool.add(i);
            }
        }

    }
}
